module.exports = class Ret {
  static CODE_PARAMETER = 1000;
  static CODE_TOKEN = 1001;
  static CODE_ROLE = 1002;
  static CODE_LOGIC = 1003;
  static CODE_SYSTEM = 1004;

  constructor(success, message, code) {
    this.success = success;
    if (message) {
      this.message = message;
    }
    if (code) {
      this.code = code;
    }
  }

  ok() {
    this.success = true;
    return this;
  }
  isOk() {
    return this.success;
  }
  fail() {
    this.success = false;
    return this;
  }
  isFail() {
    return !this.success;
  }
  setMessage(message) {
    this.message = message;
    return this;
  }
  getMessage() {
    return this.message;
  }
  setCode(code) {
    this.code = code;
    return this;
  }
  setData(data) {
    this.data = data;
    return this;
  }
  getData() {
    return this.data;
  }
  toString() {
    return JSON.stringify(this);
  }
  getJson() {
    return this;
  }
  toJson() {
    return this;
  }

  filter(props = []) {
    if (props.length > 0) {
      const data = this.data;
      if (data instanceof Array) {
        this.data = this._filterArray(data, props);
      } else {
        this.data = this._filterObject(data, props);
      }
    }
    return this;
  }

  _filterObject(target, props) {
    let result = {};
    Object.keys(target).forEach((n) => {
      if (props.includes(n)) {
        if (target[n] instanceof Array) {
          result[n] = this._filterArray(target[n], props);
        } else {
          result[n] = target[n];
        }
      }
    });
    return result;
  }

  _filterArray(target, props) {
    let result = [];
    target.forEach((n) => {
      if (n instanceof Object) {
        result.push(this._filterObject(n, props));
      } else {
        result.push(n);
      }
    });
    return result;
  }
};
